package com.ll.beautymall.ui.home.categorydetail.view;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.ll.beautymall.R;
import com.ll.beautymall.adapter.BrandAdapter;
import com.ll.beautymall.adapter.ContentGvAdapter;
import com.ll.beautymall.api.UrlConfig;
import com.ll.beautymall.base.BaseActivity;
import com.ll.beautymall.bean.Brand;
import com.ll.beautymall.bean.BrandData;
import com.ll.beautymall.bean.BrandList;
import com.ll.beautymall.bean.Category;
import com.ll.beautymall.bean.Content;
import com.ll.beautymall.bean.HomeAllBuy;
import com.ll.beautymall.ui.home.allbuy.presenter.AllBuyPresenter;
import com.ll.beautymall.ui.home.allbuy.view.IAllBuyView;
import com.ll.beautymall.ui.home.categorydetail.presenter.CategoryDetailPresenter;
import com.ll.beautymall.utils.CommonUtil;
import com.ll.beautymall.utils.NetUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class CategoryDetailActivity extends BaseActivity implements ICategoryDetailView, IAllBuyView {
    @BindView(R.id.iv_category_detail_back)
    ImageView ivCategoryDetailBack;
    @BindView(R.id.tv_category_detail_title)
    TextView tvCategoryDetailTitle;
    @BindView(R.id.tb_category_detail_toolbar)
    Toolbar tbCategoryDetailToolbar;
    @BindView(R.id.category_detail_rg)
    RadioGroup categoryDetailRg;
    @BindView(R.id.xrv_category_detail)
    XRecyclerView xrvCategoryDetail;

    private CategoryDetailPresenter presenter;
    private GridView gv_more;
    private BrandAdapter brandAdapter;
    private String cids;
    private AllBuyPresenter allBuyPresenter;
    private ContentGvAdapter allAdapter;
    private Category category;
    private List<String> leftImages;

    private boolean isOpen = false;
    private List<String> fixedImages;
    private View viewHeader;
    private TextView tv_more;
    private HashMap<String, String> request_paramters;
    private int current_page = 1;
    private int page_count;
    private int next_cursor;
    private int current_cursor = 0;
    private String sort = "default";

    @Override
    public int getLayoutId() {
        return R.layout.activity_category_detail;
    }

    @Override
    public void initView() {
        presenter = new CategoryDetailPresenter(this);
        allBuyPresenter = new AllBuyPresenter(this);
        request_paramters = new HashMap<>();

        ImageView iv_empty = new ImageView(this);
        iv_empty.setBackgroundResource(R.mipmap.img_begin_05);
        xrvCategoryDetail.setEmptyView(iv_empty);


        XRecyclerView.LayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
        xrvCategoryDetail.setLayoutManager(manager);

        xrvCategoryDetail.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadAllBuyData(false, sort, current_cursor, 40);
                xrvCategoryDetail.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                current_page++;
                if (current_page < page_count) {
                    loadAllBuyData(true, sort, next_cursor, 40);
                    xrvCategoryDetail.loadMoreComplete();
                }
            }
        });

        allAdapter = new ContentGvAdapter(this);
        xrvCategoryDetail.setAdapter(allAdapter);

        Intent intent = getIntent();

        String model = intent.getStringExtra("model");
        if (model != null) {
            String result = model.substring(model.indexOf("?") + 1);
            String title = CommonUtil.getTitle(result);
            tvCategoryDetailTitle.setText(title);
            request_paramters = CommonUtil.getParameters(result);
        }

        String bannerdetail = intent.getStringExtra("bannerdetail");
        if (bannerdetail != null) {
            String result = bannerdetail.substring(bannerdetail.indexOf("?") + 1);
            String[] split = result.split("&");
            for (int i = 0; i < split.length; i++) {
                String[] para = split[i].split("=");
                if (para[0].equals("channel_id")) {
                    continue;
                }
                if (para[0].equals("title")) {
                    try {
                        String title = URLDecoder.decode(para[1], "UTF-8");
                        tvCategoryDetailTitle.setText(title);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                request_paramters.put(para[0], para[1]);
            }
        }


        category = (Category) intent.getSerializableExtra("category");
        Content content = (Content) intent.getSerializableExtra("content");
        if (category != null && content != null) {
            tvCategoryDetailTitle.setText(category.getTitle());
            cids = category.getCids();
            request_paramters = content.getRequest_paramters();
        }

        if (cids != null) {
            request_paramters.put(UrlConfig.Key.CATEGORY_IDS, cids);
        }

        loadBrandData();
        loadAllBuyData(false, sort, current_cursor, 40);

        categoryDetailRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.category_detail_default:
                        sort = "default";
                        loadAllBuyData(false, sort, current_cursor, 40);
                        break;
                    case R.id.category_detail_sales:
                        sort = "sales";
                        loadAllBuyData(false, sort, current_cursor, 40);
                        break;
                    case R.id.category_detail_time:
                        sort = "time";
                        loadAllBuyData(false, sort, current_cursor, 40);
                        break;
                }
            }
        });
    }

    private void loadAllBuyData(boolean isMore, String cSort, int cursor, int count) {
        if (NetUtil.hasInternet(this)) {
            request_paramters.put(UrlConfig.Key.SORT, cSort);
            request_paramters.put(UrlConfig.Key.CURSOR, String.valueOf(cursor));
            request_paramters.put(UrlConfig.Key.COUNT, String.valueOf(count));
            allBuyPresenter.setAllBuyData(isMore, request_paramters);
        }
    }

    private void loadBrandData() {
        if (NetUtil.hasInternet(this)) {
            presenter.setBrandData(request_paramters);
        }
    }


    @OnClick(R.id.iv_category_detail_back)
    public void onClick(View view) {
        finish();
    }

    @Override
    public void setBrandData(BrandData brandData) {
        if (brandData == null) {
            return;
        }
        List<BrandList> brands = brandData.getContent().getBrands();
        for (int i = 0; i < brands.size(); i++) {
            if (category == null) {
                return;
            }
            if (TextUtils.equals(brands.get(i).getTitle(), category.getTitle())) {
                fixedImages = new ArrayList<>();
                leftImages = new ArrayList<>();
                cids = brands.get(i).getCids();
                List<Brand> brandList = brands.get(i).getBrandList();
                if (brandList.size() > 0) {
                    viewHeader = LayoutInflater.from(this).inflate(R.layout.category_detail_header, null);
                    gv_more = (GridView) viewHeader.findViewById(R.id.gv_brands_more);
                    tv_more = (TextView) viewHeader.findViewById(R.id.tv_open_more);

                    brandAdapter = new BrandAdapter();
                    gv_more.setAdapter(brandAdapter);
                    xrvCategoryDetail.addHeaderView(viewHeader);

                    if (tv_more != null) {
                        tv_more.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (leftImages != null) {
                                    if (!isOpen) {
                                        brandAdapter.addData(leftImages);
                                        tv_more.setText("收起");
                                        tv_more.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.delivery_moretop_sp), null);
                                        isOpen = true;
                                    } else {
                                        brandAdapter.removeData(leftImages);
                                        tv_more.setText("展开");
                                        tv_more.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.mipmap.delivery_more_sp), null);
                                        isOpen = false;
                                    }
                                }
                            }
                        });
                    }
                }
                for (int j = 0; j < brandList.size(); j++) {
                    String logo_url = brandList.get(j).getLogo_url();
                    if (j < 16) {
                        fixedImages.add(logo_url);
                    } else {
                        leftImages.add(logo_url);
                    }
                }
                //将数据全部传入，只动态改变显示的个数
                brandAdapter.setBrandList(brandList);
                brandAdapter.setData(fixedImages);
            }
        }
    }

    @Override
    public void setAllBuyData(HomeAllBuy allBuy) {
        page_count = allBuy.getPage_count();
        next_cursor = allBuy.getNext_cursor();
        allAdapter.clear();
        allAdapter.setData(allBuy.getProducts());
    }

    @Override
    public void addAllBuyData(HomeAllBuy allBuy) {
        page_count = allBuy.getPage_count();
        next_cursor = allBuy.getNext_cursor();
        allAdapter.addData(allBuy.getProducts());
    }

    @Override
    public void showErrorMsg(String msg) {
        Toast.makeText(CategoryDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}
